package com.duowan.cms.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.webapp.content.SpringApplicationContextHolder;
import com.duowan.cms.dto.channel.ChannelInfo;
import com.duowan.cms.dto.user.UserInfo;
import com.duowan.cms.service.channel.ChannelService;

public class UrlFilter  implements Filter{

	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
				throws IOException, ServletException{
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setAttribute("ROOT", "http://"+request.getHeader("host"));
        this.setChannelInfo(request, response);
        response.setCharacterEncoding("UTF-8");
        UserInfo userInfo = (UserInfo)request.getSession().getAttribute("userInfo");
        if (userInfo == null && request.getRequestURL().toString().toLowerCase().indexOf("login") == -1
        			&& request.getRequestURL().toString().indexOf("/article/uploadArticlePic.do") == -1
        			&& request.getRequestURL().toString().indexOf("/article/uploadHeadPic.do") == -1
        			&& request.getRequestURL().toString().indexOf("/file/upload.do") == -1) {
        	response.sendRedirect("/login/toLogin.do");
        	return;
		}
        filterChain.doFilter(request, response);
        
	}
	
	/**
	 * 设置当前的频道
	 * @param request
	 * @throws IOException 
	 */
	private void setChannelInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	String channelId = request.getParameter("channelId");
    	ChannelInfo channelInfo = null ;
    	if (StringUtil.isEmpty(channelId)) {
    		channelInfo = (ChannelInfo)request.getSession().getAttribute("channelInfo");
		}else{
			channelInfo = getChannelService().getById(channelId);
			if(null == channelInfo){
	            response.sendRedirect("/toPageNotFoundPage.do");
	            return ;
	        }
		}
    	
    	request.getSession().setAttribute("channelInfo", channelInfo);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
	
	private ChannelService getChannelService(){
		return SpringApplicationContextHolder.getBean("channelService", ChannelService.class);
	}

}
